package org.m2acsi.boundary;

import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.m2acsi.entities.Document;
import org.m2acsi.entities.Document_;
import org.m2acsi.entities.Task;

@Stateless
public class DocumentEJB extends BaseEJB<Document> {

    @PersistenceContext(unitName = "taskManagerPU")
    EntityManager em;

    public DocumentEJB() {
        super(Document.class);
    }

    @Override
    public void remove(Document entity) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public EntityManager em() {
        return em;
    }

    public Document findDocument(String mongoId) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Document> criteria = cb.createQuery(entityClass);
        Root<Document> root = criteria.from(entityClass);
        criteria.select(root);
        criteria.where(cb.equal(root.get(Document_.mongoId), mongoId));
        try {
            return em.createQuery(criteria).getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
    }

    public List<Document> findAll(Task task) {
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<Document> criteria = builder.createQuery(entityClass);
        Root<Document> query = criteria.from(entityClass);
        criteria.select(query);
        criteria.where(builder.equal(query.get(Document_.task), task));
        try {
            return em.createQuery(criteria).getResultList();
        } catch (Exception e) {
            return null;
        }
    }
}
